import React, { useState, useEffect, useCallback } from 'react';
import { motion } from 'framer-motion';
import { useHistory } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
import { creditsService, UserCredits, CreditTransaction, CreditPackage, CREDIT_PACKAGES } from '../services/credits';
import StripePayment from '../components/StripePayment';
import CreditPackageGrid from '../components/CreditPackageGrid';

interface Transaction {
  id: string;
  amount: number;
  credits: number;
  status: string;
  createdAt: string;
  packageName?: string;
}

const ProfileBilling: React.FC = () => {
  const [userCredits, setUserCredits] = useState<UserCredits | null>(null);
  const [transactions, setTransactions] = useState<CreditTransaction[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState('');
  
  // 购买积分相关状态
  const [creditPackages, setCreditPackages] = useState<CreditPackage[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [isLoadingCredits, setIsLoadingCredits] = useState(true);
  const [showPaymentModal, setShowPaymentModal] = useState(false);
  const [selectedPackage, setSelectedPackage] = useState<CreditPackage | null>(null);
  const [showBuyCredits, setShowBuyCredits] = useState(true);
  
  const { user, isAuthenticated } = useAuth();
  const history = useHistory();

  // 加载用户积分信息 - 使用useCallback避免依赖问题
  const loadUserCredits = useCallback(async () => {
    if (!user) return;
    
    setIsLoadingCredits(true);
    try {
      const credits = await creditsService.getUserCredits(user.id);
      setUserCredits(credits);
      console.log('Loaded user credits:', credits); // 添加日志以便调试
    } catch (error: any) {
      console.error('Failed to load user credits:', error);
      setError('Failed to load credit information');
    } finally {
      setIsLoadingCredits(false);
    }
  }, [user]);

  // 加载积分包列表
  const loadCreditPackages = async () => {
    try {
      const packages = await creditsService.getCreditPackages();
      setCreditPackages(packages);
    } catch (error: any) {
      console.error('Failed to load credit packages:', error);
      // 使用fallback数据
      setCreditPackages(CREDIT_PACKAGES);
    }
  };

  useEffect(() => {
    if (user) {
      loadUserData();
      loadCreditPackages();
    } else {
      setLoading(false);
    }
  }, [user]);

  const loadUserData = async () => {
    try {
      setLoading(true);
      if (user) {
        // 加载用户积分
        const creditsResponse = await creditsService.getUserCredits(user.id);
        console.log('Loaded user credits in loadUserData:', creditsResponse);
        setUserCredits(creditsResponse);

        // 加载用户交易记录
        const transactionsResponse = await creditsService.getUserTransactions(user.id);
        setTransactions(transactionsResponse);
      }
    } catch (err) {
      console.error('Error loading user data:', err);
      setError('Failed to load billing information');
    } finally {
      setLoading(false);
      setIsLoadingCredits(false); // 确保加载状态被正确设置
    }
  };

  const handleBuyCredits = () => {
    setShowBuyCredits(true);
  };
  
  // 处理购买按钮点击
  const handlePurchase = async (creditPackage: CreditPackage) => {
    // 检查用户是否登录
    if (!isAuthenticated || !user) {
      setError('Please login first to purchase credits');
      return;
    }

    // 显示支付弹窗
    setSelectedPackage(creditPackage);
    setShowPaymentModal(true);
    setError(null);
    setSuccess('');
  };

  // 处理支付成功
  const handlePaymentSuccess = async (paymentIntent: any) => {
    if (!selectedPackage || !user) return;

    setIsLoading(true);
    setShowPaymentModal(false);

    try {
      // 调用后端API处理支付成功
      const updatedCredits = await creditsService.handlePaymentSuccess(
        user.id,
        selectedPackage.id,
        paymentIntent.id
      );
      
      setUserCredits(updatedCredits);
      setSuccess(`Successfully purchased ${selectedPackage.credits} credits! Your new balance is ${updatedCredits.creditBalance} credits.`);
      
      // 重新加载交易记录
      loadUserData();
      
      // 清除成功消息
      setTimeout(() => {
        setSuccess('');
      }, 10000);
    } catch (error: any) {
      setError(error.message || 'Failed to process payment. Please contact support if credits were charged.');
    } finally {
      setIsLoading(false);
      setSelectedPackage(null);
    }
  };

  // 处理支付错误
  const handlePaymentError = (errorMessage: string) => {
    setError(errorMessage);
    setShowPaymentModal(false);
    setSelectedPackage(null);
    
    setTimeout(() => {
      setError(null);
    }, 5000);
  };

  // 处理支付取消
  const handlePaymentCancel = () => {
    setShowPaymentModal(false);
    setSelectedPackage(null);
  };

  // 格式化过期信息显示
  const formatExpirationInfo = () => {
    if (!userCredits) return null;
    
    const expirationInfo = creditsService.formatExpirationInfo(userCredits);
    
    if (!expirationInfo.message) return null;
    
    const colorClass = {
      'error': 'text-red-600',
      'warning': 'text-orange-600',
      'info': 'text-gray-600'
    }[expirationInfo.type || 'info'];

    return (
      <div className={`text-sm ${colorClass}`}>
        {expirationInfo.message}
      </div>
    );
  };

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
    });
  };

  const getStatusBadgeClass = (status: string) => {
    switch (status.toLowerCase()) {
      case 'completed':
      case 'succeeded':
        return 'bg-green-100 text-green-800';
      case 'pending':
        return 'bg-yellow-100 text-yellow-800';
      case 'failed':
        return 'bg-red-100 text-red-800';
      default:
        return 'bg-gray-100 text-gray-800';
    }
  };

  if (!user) {
    return (
      <div className="min-h-screen bg-gradient-to-b from-gray-50 to-gray-100 flex items-center justify-center">
        <div className="text-center">
          <h2 className="text-2xl font-bold text-gray-900 mb-4">Please log in to view your billing</h2>
          <p className="text-gray-600">You need to be logged in to access your billing information.</p>
        </div>
      </div>
    );
  }

  if (loading) {
    return (
      <div className="min-h-screen bg-gradient-to-b from-gray-50 to-gray-100 flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <p className="text-gray-600">Loading your billing information...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-b from-gray-50 to-gray-100 py-12">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="text-center mb-12">
          <h1 className="text-4xl font-bold text-gray-900 mb-4">Billing & Credits</h1>
          <p className="text-xl text-gray-600">Manage your credits and view transaction history</p>
        </div>

        <div className="max-w-6xl mx-auto">
          {/* Credit Summary */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.3 }}
            className="bg-white rounded-2xl shadow-xl overflow-hidden mb-8"
          >
            <div className="bg-gradient-to-r from-blue-600 to-indigo-700 p-6 md:p-8">
              <h2 className="text-2xl font-bold text-white">Credit Balance</h2>
              <p className="text-blue-100 mt-1">Your current credit status</p>
            </div>

            <div className="p-6 md:p-8">
              <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                <div className="bg-gradient-to-br from-blue-50 to-indigo-50 rounded-xl p-6 text-center">
                  <p className="text-gray-500 text-sm mb-1">Available Credits</p>
                  <p className="text-4xl font-bold text-blue-600">
                    {isLoadingCredits ? (
                      <span className="inline-block w-12 h-8 bg-blue-100 animate-pulse rounded"></span>
                    ) : (
                      userCredits?.creditBalance || 0
                    )}
                  </p>
                </div>

                <div className="bg-gradient-to-br from-green-50 to-emerald-50 rounded-xl p-6 text-center">
                  <p className="text-gray-500 text-sm mb-1">Expiration</p>
                  <p className="text-4xl font-bold text-emerald-600">
                    {isLoadingCredits ? (
                      <span className="inline-block w-24 h-8 bg-emerald-100 animate-pulse rounded"></span>
                    ) : (
                      userCredits?.expiresAt ? formatDate(userCredits.expiresAt) : 'Never'
                    )}
                  </p>
                </div>

                <div className="bg-gradient-to-br from-purple-50 to-pink-50 rounded-xl p-6 text-center">
                  <p className="text-gray-500 text-sm mb-1">Days Remaining</p>
                  <p className="text-4xl font-bold text-purple-600">
                    {isLoadingCredits ? (
                      <span className="inline-block w-8 h-8 bg-purple-100 animate-pulse rounded"></span>
                    ) : (
                      userCredits?.daysUntilExpiration || '∞'
                    )}
                  </p>
                </div>
              </div>
            </div>
          </motion.div>

          {/* 购买积分部分 */}
          {showBuyCredits && (
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.3, delay: 0.1 }}
              className="bg-white rounded-2xl shadow-xl overflow-hidden mb-8"
            >
              <div className="bg-gradient-to-r from-purple-600 to-pink-600 p-6 md:p-8">
                <div className="flex justify-between items-center">
                  <div>
                    <h2 className="text-2xl font-bold text-white">Buy Credits</h2>
                    <p className="text-purple-100 mt-1">Purchase credits to use our AI room design features</p>
                  </div>
                  <button 
                    onClick={() => setShowBuyCredits(false)}
                    className="text-white hover:text-purple-200 transition-colors"
                  >
                    <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                    </svg>
                  </button>
                </div>
              </div>

              <div className="p-6 md:p-8">
                {/* 全局消息显示 */}
                {error && (
                  <motion.div
                    initial={{ opacity: 0, scale: 0.95 }}
                    animate={{ opacity: 1, scale: 1 }}
                    className="mb-6 bg-red-50 border border-red-200 text-red-600 px-4 py-3 rounded-lg"
                    role="alert"
                  >
                    <span className="block sm:inline">{error}</span>
                  </motion.div>
                )}

                {success && (
                  <motion.div
                    initial={{ opacity: 0, scale: 0.95 }}
                    animate={{ opacity: 1, scale: 1 }}
                    className="mb-6 bg-green-50 border border-green-200 text-green-600 px-4 py-3 rounded-lg"
                    role="alert"
                  >
                    <span className="block sm:inline">{success}</span>
                  </motion.div>
                )}

                {/* 积分包选择 */}
                <CreditPackageGrid
                  creditPackages={creditPackages}
                  isLoading={isLoading}
                  isAuthenticated={isAuthenticated}
                  onPurchase={handlePurchase}
                  defaultHighlightIndex={1}
                />

                {/* FAQ部分 */}
                <div className="mt-16 bg-gray-50 rounded-xl p-8">
                  <h2 className="text-2xl font-bold text-gray-900 mb-6">Frequently Asked Questions</h2>
                  <div className="space-y-6">
                    <div>
                      <h3 className="text-lg font-medium text-gray-900 mb-2">How do credits work?</h3>
                      <p className="text-gray-700">
                        Each credit allows you to generate one AI room redesign. Simply upload a photo of your room,
                        select a style, and use one credit to see the transformation.
                      </p>
                    </div>
                    <div>
                      <h3 className="text-lg font-medium text-gray-900 mb-2">How long are credits valid for?</h3>
                      <p className="text-gray-700">
                        Credits are valid for the period specified in your plan (30, 60, or 90 days from purchase).
                        We'll remind you before they expire.
                      </p>
                    </div>
                    <div>
                      <h3 className="text-lg font-medium text-gray-900 mb-2">Can I get a refund?</h3>
                      <p className="text-gray-700">
                        We currently do not offer refunds for purchased credits. If you have any issues,
                        please contact our support team.
                      </p>
                    </div>
                    <div>
                      <h3 className="text-lg font-medium text-gray-900 mb-2">Is payment secure?</h3>
                      <p className="text-gray-700">
                        We use industry-leading Stripe payment processing to ensure your payment information is secure.
                        We never store your credit card information.
                      </p>
                    </div>
                  </div>
                </div>
              </div>
            </motion.div>
          )}

          {/* Transaction History */}
          {/* <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.3, delay: 0.1 }}
            className="bg-white rounded-2xl shadow-xl overflow-hidden"
          >
            <div className="bg-gradient-to-r from-gray-700 to-gray-900 p-6 md:p-8">
              <h2 className="text-2xl font-bold text-white">Transaction History</h2>
              <p className="text-gray-300 mt-1">Your recent credit transactions</p>
            </div>

            <div className="p-6 md:p-8">
              {transactions.length > 0 ? (
                <div className="overflow-x-auto">
                  <table className="w-full">
                    <thead>
                      <tr className="border-b border-gray-200">
                        <th className="text-left py-3 px-4 text-gray-600 text-sm font-medium">Date</th>
                        <th className="text-left py-3 px-4 text-gray-600 text-sm font-medium">Transaction</th>
                        <th className="text-left py-3 px-4 text-gray-600 text-sm font-medium">Credits</th>
                        <th className="text-left py-3 px-4 text-gray-600 text-sm font-medium">Status</th>
                      </tr>
                    </thead>
                    <tbody>
                      {transactions.map((transaction) => (
                        <tr key={transaction.id} className="border-b border-gray-100 hover:bg-gray-50">
                          <td className="py-3 px-4 text-gray-800">{formatDate(transaction.createdAt)}</td>
                          <td className="py-3 px-4 text-gray-800">
                            {transaction.description || transaction.transactionType}
                          </td>
                          <td className="py-3 px-4">
                            <span className={transaction.creditAmount > 0 ? 'text-green-600' : 'text-red-600'}>
                              {transaction.creditAmount > 0 ? '+' : ''}{transaction.creditAmount}
                            </span>
                          </td>
                          <td className="py-3 px-4">
                            <span className={`px-2 py-1 rounded-full text-xs font-medium ${getStatusBadgeClass(transaction.transactionType)}`}>
                              {transaction.transactionType}
                            </span>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              ) : (
                <div className="text-center py-12">
                  <p className="text-gray-500">No transactions found</p>
                </div>
              )}
            </div>
          </motion.div> */}
        </div>
      </div>

      {/* 支付弹窗 */}
      {showPaymentModal && selectedPackage && user && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
          <motion.div
            initial={{ opacity: 0, scale: 0.95 }}
            animate={{ opacity: 1, scale: 1 }}
            className="bg-white rounded-xl shadow-xl max-w-md w-full max-h-[90vh] overflow-y-auto"
          >
            <div className="p-6">
              <div className="flex justify-between items-center mb-6">
                <h3 className="text-xl font-bold text-gray-900">
                  Purchase {selectedPackage.name}
                </h3>
                <button
                  onClick={handlePaymentCancel}
                  className="text-gray-400 hover:text-gray-600"
                >
                  <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                  </svg>
                </button>
              </div>

              <StripePayment
                creditPackage={selectedPackage}
                userId={user.id.toString()}
                onSuccess={handlePaymentSuccess}
                onError={handlePaymentError}
                onCancel={handlePaymentCancel}
              />
            </div>
          </motion.div>
        </div>
      )}

      {/* 加载遮罩 */}
      {isLoading && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg p-6 flex items-center">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mr-3"></div>
            <span className="text-gray-700">Processing your purchase...</span>
          </div>
        </div>
      )}
    </div>
  );
};

export default ProfileBilling;